package com.hzlh.shiro;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.hzlh.domain.po.LoginAdmin;
import com.hzlh.domain.po.RolePo;
import com.hzlh.service.RolePermService;
import com.hzlh.service.UserService;

public class ShiroDbRealm extends AuthorizingRealm {

	@Autowired
	protected UserService userService;
	@Autowired
	protected RolePermService rolePermService;
	
	/**
	 * 认证回调函数, 登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		/**
		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
		
		String parm = token.getCaptcha();
		String c = (String)SecurityUtils.getSubject().getSession()
				.getAttribute(SimpleCaptchaServlet.CAPTCHA_KEY);
		// 忽略大小写
		if (!parm.equalsIgnoreCase(c)) {
			throw new IncorrectCaptchaException("验证码错误！"); 
		} 
		**/
		
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		String userName = token.getUsername(); 
		//由于参数位不够，sysCode用host的参数位传递进来    zhanjp added
		String sysCode = token.getHost();
		if( userName != null && !"".equals(userName) ){
			LoginAdmin loginUser = new LoginAdmin();
			loginUser.setUserId(userName);
			loginUser.setPwd(String.valueOf(token.getPassword()));
			LoginAdmin user = userService.login(loginUser);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sysCode", sysCode);
			System.out.println(">>>>>>>>>>>>>>>>  当前登录云听>>>" + sysCode);
			//获取系统配置表中的配置，供以后代码合并使用
//			SystemInitPo sysInitPo = systemInitService.getBySystemCode(map);
			if (user != null) {
				ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUserId(), user);
//				shiroUser.setSysInit(sysInitPo);
				return new SimpleAuthenticationInfo(shiroUser, user.getPwd() , getName());
			} 
		}
		return null;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName()).iterator().next();
		if(shiroUser == null){
			return null;
		}
		//获取最新权限
		LoginAdmin loginAdmin = null;
		List<RolePo> userRoles = null;
		if(shiroUser.getUser() != null){
			loginAdmin = shiroUser.getUser();
			userRoles = loginAdmin.getRoles();
		}else{
			loginAdmin = userService.getUser(shiroUser.getId());
			userRoles = loginAdmin.getRoles();
		}
		
		if (!userRoles.isEmpty()) {
			shiroUser.getUser().setRoles(userRoles);
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (RolePo userRole : userRoles) {
				//基于Permission的权限信息
				List<String> list = rolePermService.getRoleAuthorizNames(userRole.getId());
				if(list.size() > 0){
					info.addStringPermissions(list);
				}
			}
			return info;
		}
		return null;
	}
	
	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}
	
}
